package com.zhht.htzx.ui;

import static com.nsgf.library.photopicker.PhotoPicker.EXTRA_VIEW_ID;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.glide.GlideImgManager;
import com.nsgf.library.matisse.Matisse;
import com.nsgf.library.matisse.MimeType;
import com.nsgf.library.matisse.engine.impl.GlideEngine;
import com.nsgf.library.matisse.internal.entity.CaptureStrategy;
import com.nsgf.library.matisse.listener.OnCheckedListener;
import com.nsgf.library.matisse.listener.OnSelectedListener;
import com.nsgf.library.photopicker.PhotoPicker;
import com.nsgf.library.photopicker.utils.PermissionsUtils;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.ToastUtils;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.ActivityUserInfoBinding;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 个人信息
 */
public class UserInfoActivity extends BaseActivity {

    private UserInfoStates mStates;

    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(UserInfoStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);

    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_user_info, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy());
    }

    private ActivityUserInfoBinding mBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mStates.titleBar.set("个人信息");
        mBinding = (ActivityUserInfoBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);
        mStates.userName.set(mStates.name.get());
        mStates.avatar.set(UserInfo.getInstance().getAppLog());

        mAccountRequester.getSrcSuccess().observe(this, new Observer<ResponseStatus<String>>() {
            @Override
            public void onChanged(ResponseStatus<String> stringResponseStatus) {
                getController().dismissLoading();
                if (stringResponseStatus.getResponseCode() == 0) {
                    ToastUtils.showShortToast(stringResponseStatus.getMsg());
                    finish();
                }
            }
        });

        mAccountRequester.getStringResult().observe(this, new Observer<ResponseStatus<Object>>() {
            @Override
            public void onChanged(ResponseStatus<Object> dataResult) {
                if (dataResult.getResponseCode() == 0) {
                    mStates.userHead.set(dataResult.getData().toString());
                    httpUserInfo();
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (RESULT_OK == resultCode) {
            if (PhotoPicker.REQUEST_CODE == requestCode) {
                ArrayList<WorkOrderDetailBean.FileDto> photos = new ArrayList<>();
                for (String src : Matisse.obtainPathResult(data)) {
                    WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                    dto.setFilePath(src);
                    photos.add(dto);
                    GlideImgManager.getInstance().glideLoaderCenterCrop(UserInfoActivity.this,
                            new File(src),
                            mBinding.ivUserHead);
                    mStates.userHead.set(src);
                }
            }
        }
    }

    public static class UserInfoStates extends StateHolder {

        public final State<String> userHead = new State<>("");
        public final State<String> userName = new State<>("");
    }

    public class ClickProxy {

        public void openPhoto() {

            String[] permission;

            Set<MimeType> mimeTypes = MimeType.ofImage();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                permission = new String[]{Manifest.permission.READ_MEDIA_IMAGES,
                        Manifest.permission.READ_MEDIA_VIDEO,
                        Manifest.permission.READ_MEDIA_AUDIO};
            } else {
                permission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA};
            }
            boolean checkPermissionFirst = PermissionsUtils.checkPermissionFirst(UserInfoActivity.this, 203, permission);
            if (checkPermissionFirst) {
                Matisse.from(UserInfoActivity.this)
                        .choose(mimeTypes, false)
                        .capture(false) //默认只能拍照片
                        .captureStrategy(
                                new CaptureStrategy(true, "com.zhht.htzx.fileprovider", "photo"))
                        //.capture(true, CaptureMode.All)//通过CaptureMode控制拍照照片还是视频，或者都拍
                        .maxSelectable(1) //默认最大选中9张，设置为1就是单选
                        .theme(R.style.Matisse_Dracula)//暗色主题
                        //设置选中图片的监听器
                        .setOnSelectedListener(new OnSelectedListener() {
                            @Override
                            public void onSelected(
                                    @NonNull List<Uri> uriList, @NonNull List<String> pathList) {
                                // DO SOMETHING IMMEDIATELY HERE
                                Log.e("onSelected", "onSelected: pathList=" + pathList);

                            }
                        })
                        .originalEnable(true)//是否显示原图，默认显示
                        //设置原图选中和取消选中的监听器
                        .setOnCheckedListener(new OnCheckedListener() {
                            @Override
                            public void onCheck(boolean isChecked) {
                                // DO SOMETHING IMMEDIATELY HERE
                                Log.e("isChecked", "onCheck: isChecked=" + isChecked);
                            }
                        })
                        .setSelectedImages(new ArrayList<>())
                        .imageEngine(new GlideEngine()) // 默认是Glide4.x版本的加载器，如果你用的是Glide4.x，则无需设置
                        .forResult(PhotoPicker.REQUEST_CODE); //请求码


            }
        }

        public void updateUserInfo() {
            getController().displayLoading();
            if (mStates.avatar.get().equals(mStates.userHead.get())) {

                httpUserInfo();
            } else {

                mAccountRequester.uploadFile(mStates.userHead.get());

            }
        }
    }

    private void httpUserInfo() {

        JsonObject params = new JsonObject();
        params.addProperty("nickname", mStates.userName.get());
        params.addProperty("avatar", mStates.userHead.get());
        mAccountRequester.updateUser(params);
    }
}
